<template>
  <div class="password-strength-container">
    <!-- 强度提示文字 -->
    <div class="strength-text">
      密码强度：<span :style="{ color: strengthColor }">{{ strengthLabel }}</span>
    </div>

    <!-- 强度指示条 -->
    <div class="strength-bars">
      <div
          v-for="n in 4"
          :key="n"
          class="strength-bar"
          :class="{
          'active': n <= strengthLevel,
          [strengthClass]: n <= strengthLevel
        }"
      ></div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  password: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['strength-change'])

// 强度等级计算逻辑（5级划分）
const calculateStrength = (pwd) => {
  if (!pwd) return 0

  let score = 0
  const rules = [
    pwd.length >= 6,                  // 长度达标
    /\d/.test(pwd),                   // 包含数字
    /[a-z]/.test(pwd),                // 包含小写字母
    /[A-Z]/.test(pwd),                // 包含大写字母
    /[^a-zA-Z0-9]/.test(pwd)          // 包含特殊字符
  ]

  // 基础分计算
  score += pwd.length >= 12 ? 2 : (pwd.length >= 6 ? 1 : 0)
  score += rules.filter(Boolean).length

  return Math.min(score, 5) // 最大5级
}

// 响应式强度等级
const strengthLevel = ref(0)
const strengthLabel = computed(() =>
    ['极弱', '弱', '一般', '强', '非常强'][strengthLevel.value - 1] || ''
)

const strengthColor = computed(() => {
  const colors = ['#ff4d4f', '#ff7a45', '#faad14', '#a0d911', '#52c41a']
  return colors[strengthLevel.value - 1] || '#d9d9d9'
})

const strengthClass = computed(() => `level-${strengthLevel.value}`)

watch(() => props.password, (newVal) => {
  strengthLevel.value = calculateStrength(newVal)
  emit('strength-change', strengthLevel.value)
}, { immediate: true })
</script>

<style scoped lang="scss">
.password-strength-container {
  margin: 12px 0;
  width: 100%;

  .strength-text {
    font-size: 12px;
    color: #666;
    margin-bottom: 8px;

    span {
      font-weight: 500;
    }
  }

  .strength-bars {
    display: flex;
    gap: 2px;
    height: 6px;

    .strength-bar {
      flex: 1;
      background: #f0f0f0;
      border-radius: 2px;
      transition: all 0.3s ease;

      &.active {
        &.level-1 { background: #ff4d4f; }
        &.level-2 { background: #ff7a45; }
        &.level-3 { background: #faad14; }
        &.level-4 { background: #a0d911; }
        &.level-5 { background: #52c41a; }
      }
    }
  }
}
</style>